import {
    ProForm,
    ProFormGroup,
    ProFormItem,
    ProFormSelect,
    ProFormSwitch,
    ProFormText,
    ProFormTextArea
} from '@ant-design/pro-components';
import { Button } from 'antd';
import React, { CSSProperties, useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';

import { CLASS_ATTRIBUTE_CLASS_IDENTIFIER } from '@/services/constants';
import { dsBatchInsert, dsFindOne, dsInsert, dsUpdateById, ComparsionOperator } from '@/services/local';
import { COLLECTION_TYPE_SELECT_OPTIONS, MetaDataObjectProperty, VALUE_SIZE_SELECT_OPTIONS, VALUE_TYPE_SELECT_OPTIONS, ValueSize } from '../../../services';
import { uuid } from '../../../utils';

export interface ObjectPropertyEditorProps {
    style?: CSSProperties;
    objectIdentifier: string;
    item?: MetaDataObjectProperty;
    onFinish: () => Promise<void> | void;
}

export const ObjectPropertyEditor: React.FC<ObjectPropertyEditorProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const requestCallback = useCallback(async () => {
        console.log('---------', props.item);
        if (!props.item) return {};
        return props.item;
    }, [props.item]);

    useEffect(() => { }, [props.item])

    return (
        <Container style={{ ...props.style }}>
            <ProForm<MetaDataObjectProperty>
                initialValues={props.item}
                request={requestCallback}
                onFinish={async (values) => {
                    //TODO 校验
                    values = {
                        class_identifier: props.objectIdentifier,
                        ...props.item,
                        ...values,
                    };
                    if (props.item) {
                        //编辑
                        await dsUpdateById(0, CLASS_ATTRIBUTE_CLASS_IDENTIFIER, props.item.id, values);
                        // let _ = await metaDataUpdateObjectProperty(values);
                    } else {
                        //添加
                        values.identifier = uuid();
                        let _ = await dsInsert(0, CLASS_ATTRIBUTE_CLASS_IDENTIFIER, values);
                        // let _ = await metaDataSaveObjectProperty(values);
                    }
                    await props.onFinish();
                }}
                submitter={false}
            >

                <ProFormGroup>
                    <ProFormText
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="name"
                        label="名称" />

                    <ProFormText
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        name="title"
                        label="标题" />
                    <ProFormSelect
                        rules={[{ required: true }]}
                        fieldProps={{}}
                        options={VALUE_TYPE_SELECT_OPTIONS}
                        name="data_type"
                        label="数据类型" />
                </ProFormGroup>


                <ProFormGroup>
                    <ProFormSelect
                        fieldProps={{}}
                        options={COLLECTION_TYPE_SELECT_OPTIONS}
                        name="collection_type"
                        label="集合类型" />

                    <ProFormSelect
                        fieldProps={{}}
                        options={VALUE_SIZE_SELECT_OPTIONS}
                        name="value_size"
                        label="值大小" />

                    <ProFormSwitch
                        width="xl" fieldProps={{}}
                        name="is_key"
                        label="是否是主键" />

                    <ProFormSwitch
                        width="xl" fieldProps={{}}
                        name="is_autoincrement"
                        label="是否自增" />
                    <ProFormSwitch
                        fieldProps={{}}
                        name="is_number"
                        label="是否是数字" />
                    <ProFormSwitch
                        fieldProps={{}}
                        name="is_nullable"
                        label="是否可为空" />

                    <ProFormText
                        fieldProps={{}}
                        name="position"
                        label="顺序" />
                    <ProFormText
                        fieldProps={{}}
                        name="unit"
                        label="单位" />

                    <ProFormText
                        fieldProps={{}}
                        name="default_value"
                        label="默认值" />
                    <ProFormText
                        fieldProps={{}}
                        name="scope"
                        label="范围" />
                    <ProFormText
                        fieldProps={{}}
                        name="comment"
                        label="注释" />

                </ProFormGroup>

                <ProFormText
                    width="xl" fieldProps={{}}
                    name="options"
                    label="附加信息" />

                <ProFormTextArea
                    width="xl"
                    fieldProps={{}}
                    name="description"
                    label="描述" />

                <ProFormItem>
                    <Button loading={loading} type="primary" htmlType="submit">
                        添加
                    </Button>
                </ProFormItem>
            </ProForm>
        </Container>
    );
}



export const QuickObjectPropertyEditor: React.FC<ObjectPropertyEditorProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    useEffect(() => { }, [props.item])

    return (
        <Container>
            <ProForm<{ names: string }>
                initialValues={props.item}
                onFinish={async (values) => {
                    //TODO 校验
                    //values.names
                    let names = values.names;

                    let lists = names.replaceAll("，", ",").replaceAll(" ", ",").split(",");

                    let existList = [];
                    for (let i = 0; i < lists.length; i++) {
                        try {
                            let res = await dsFindOne(0, CLASS_ATTRIBUTE_CLASS_IDENTIFIER, {
                                attributes: [{
                                    name: 'name',
                                    operator: ComparsionOperator.Equal,
                                    value: lists[i]
                                }]
                            });
                            existList.push(res);
                        } catch (e) {
                            existList.push(lists[i]);
                        }
                    }
                    //通过名称查询类似的属性
                    let attributes = existList.map((item, index) => {
                        if (typeof item === 'string') {
                            let identifier = uuid();
                            return [CLASS_ATTRIBUTE_CLASS_IDENTIFIER, {
                                class_identifier: props.objectIdentifier,
                                identifier: identifier,
                                name: item,
                                title: item,
                                is_key: false,
                                data_type: 'string',
                                collection_type: 'single',
                                value_size: ValueSize.Medium,
                                is_number: false,
                                persistent: true,
                                is_autoincrement: false,
                                unit: '',
                                default_value: '',
                                is_nullable: false,
                                position: 0,
                                scope: '',
                                comment: '',
                                options: '',
                                description: '',
                            }];
                        } else {
                            let identifier = uuid();
                            item.identifier = identifier;
                            item.class_identifier = props.objectIdentifier;
                            item.id = undefined;
                            return [CLASS_ATTRIBUTE_CLASS_IDENTIFIER, item];
                        }

                    });
                    //批量添加
                    let _ = await dsBatchInsert(0, attributes);
                    await props.onFinish();
                }}
                submitter={false}
            >

                <ProFormTextArea
                    width="xl"
                    fieldProps={{}}
                    name="names"
                    extra="可以输入多个例如：id,identifier,name,title,options,description,created_at,updated_at"
                    label="输入属性名称" />

                <ProFormItem>
                    <Button loading={loading} type="primary" htmlType="submit">
                        添加
                    </Button>
                </ProFormItem>
            </ProForm>
        </Container >
    );
}


const Container = styled.div`
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
`;